import {
  actionCol,
  apiTreeSelectField,
  dictCol,
  numberField,
  selectField,
  serialCol,
  textCol,
  textField,
  type VbenFormSchema,
  type VxeGridPropTypes,
} from '#/adapter';

export const columns: VxeGridPropTypes.Columns = [
  serialCol('seq'),
  textCol('deptName', '部门名称', {
    treeNode: true,
    minWidth: 200,
    align: 'left',
  }),
  textCol('deptCode', '部门编码'),
  textCol('deptLevel', '部门等级'),
  textCol('deptLeaderName', '负责人'),
  textCol('deptPhone', '联系方式'),
  textCol('deptSort', '部门排序'),
  dictCol('deptStatus', '部门状态'),
  textCol('createName', '创建人'),
  textCol('createTime', '创建时间'),
  actionCol('actions'),
];

import { useDepartmentOptions } from '#/hooks';
export function getFormSchema(): VbenFormSchema[] {
  const { loadAllDeptTree } = useDepartmentOptions();
  return [
    apiTreeSelectField(
      'pId',
      '上级部门',
      {
        api: loadAllDeptTree,
      },
      { rules: 'required' },
    ),
    textField('deptName', '部门名称', { rules: 'required' }),
    textField('deptCode', '部门编码', { rules: 'required' }),
    numberField('deptLeaderId', '部门等级', { rules: 'required' }),
    selectField('deptStatus', '部门状态'),
    numberField('deptSort', '部门排序', { rules: 'required' }),
  ];
}

/**
 * 递归踢平深层树结构
 * @param {Array} tree - 要处理的树结构数组
 * @param {string} childrenKey - 子节点属性名(默认为'children')
 * @returns {Array} 踢平后的数组
 */
export function flattenTree(tree: any[], childrenKey = 'children') {
  if (!Array.isArray(tree)) return [];
  // eslint-disable-next-line unicorn/no-array-reduce
  return tree.reduce((acc, node) => {
    // 复制当前节点，去除children属性
    const newNode = { ...node, children: null };
    // 将当前节点加入结果数组
    acc.push(newNode);
    // 如果有子节点，递归处理
    if (node[childrenKey] && Array.isArray(node[childrenKey])) {
      const flattenedChildren = flattenTree(node[childrenKey], childrenKey);
      acc.push(...flattenedChildren);
    }
    return acc;
  }, []);
}
